package com.chatplus.application.controller.api;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chatplus.application.aiprocessor.platform.image.sd.SdImageProcessor;
import com.chatplus.application.common.exception.BadRequestException;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.common.page.PageParam;
import com.chatplus.application.common.util.PlusJsonUtils;
import com.chatplus.application.domain.dto.SdParamsDto;
import com.chatplus.application.domain.entity.draw.SdJobEntity;
import com.chatplus.application.domain.request.ImagePublishRequest;
import com.chatplus.application.domain.request.SdImageJobRequest;
import com.chatplus.application.domain.response.SdJobDetailApiResponse;
import com.chatplus.application.service.draw.SdJobService;
import com.chatplus.application.web.basecontroller.BaseController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

/**
 * SD API
 *
 * @Author: Angus
 */
@Validated
@RestController
@RequestMapping("/api/sd")
@Tag(name = "产品API", description = "SD API")
public class SdJobApiController extends BaseController {

    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(SdJobApiController.class);
    private final SdJobService sdJobService;

    private final SdImageProcessor sdImageProcessor;

    public SdJobApiController(SdJobService sdJobService,
                              SdImageProcessor sdImageProcessor) {
        this.sdJobService = sdJobService;
        this.sdImageProcessor = sdImageProcessor;
    }

    /**
     * 获取任务列表或者创作记录
     *
     * @param status 状态 0 就是不成功的，1 就是成功的
     * @return 任务列表
     */
    @GetMapping("/jobs")
    @Operation(summary = "获取任务列表或者创作记录")
    public List<SdJobDetailApiResponse> jobs(@RequestParam String status,
                                             @RequestParam(value = "page", defaultValue = "0", required = false) Integer page,
                                             @RequestParam(value = "page_size", defaultValue = "0", required = false) Integer pageSize) {
        if (page == 0 && pageSize == 0) {
            page = 1;
            pageSize = Math.toIntExact(sdJobService.getRunningJobCount(getUserId())) + 10;
        }
        PageParam pageParam = new PageParam(page, pageSize);
        Page<SdJobEntity> pageDTO = null;
        if ("0".equals(status)) {
            // 获取失败的任务
            pageDTO = sdJobService.getSdJobPage(pageParam, false, getUserId(), null);
        } else if ("1".equals(status)) {
            // 获取成功的任务
            pageDTO = sdJobService.getSdJobPage(pageParam, true, getUserId(), null);
        }
        if (pageDTO == null || CollUtil.isEmpty(pageDTO.getRecords())) {
            return Collections.emptyList();
        }
        return pageDTO.getRecords().stream().map(SdJobDetailApiResponse::build).toList();
    }

    @GetMapping("/imgWall")
    @Operation(summary = "获取任务列表或者创作记录")
    public List<SdJobDetailApiResponse> imgWall(@RequestParam(value = "page", defaultValue = "0", required = false) Integer page,
                                                @RequestParam(value = "page_size", defaultValue = "0", required = false) Integer pageSize) {
        PageParam pageParam = new PageParam(page, pageSize);
        // 获取成功的任务
        Page<SdJobEntity> pageDTO = sdJobService.getSdJobPage(pageParam, true, null, true);
        if (pageDTO == null || CollUtil.isEmpty(pageDTO.getRecords())) {
            return Collections.emptyList();
        }
        return pageDTO.getRecords().stream().map(SdJobDetailApiResponse::build).toList();
    }

    /**
     * 画图任务
     */
    @PostMapping("/image")
    @Operation(summary = "画图任务")
    public void image(@RequestBody SdImageJobRequest request) {
        String errMsg = sdImageProcessor.verifyUserRequest(getUserId());
        if (StringUtils.isNotEmpty(errMsg)) {
            throw new BadRequestException(errMsg);
        }
        initMjJobEntity(request);
        sdImageProcessor.process(request);
    }

    private void initMjJobEntity(SdImageJobRequest request) {
        SdJobEntity sdJobEntity = new SdJobEntity();
        sdJobEntity.setUserId(getUserId());
        sdJobEntity.setProgress(0);
        sdJobEntity.setPrompt(request.getPrompt());
        sdJobEntity.setParams(PlusJsonUtils.parseObject(PlusJsonUtils.toJsonString(request), SdParamsDto.class));
        sdJobService.save(sdJobEntity);
        request.setSdJobId(sdJobEntity.getId());
        request.setUserId(getUserId());

    }
    /**
     * 删除图片
     */
    @PostMapping("/remove")
    @Operation(summary = "删除图片")
    public void remove(@RequestBody ImagePublishRequest request) {
        sdJobService.removeById(request.getId());
    }

    /**
     * 发布图片
     */
    @PostMapping("/publish")
    @Operation(summary = "发布图片")
    public void publish(@RequestBody ImagePublishRequest request) {
        sdJobService.update(new LambdaUpdateWrapper<SdJobEntity>()
                .set(SdJobEntity::getPublish, request.isAction())
                .eq(SdJobEntity::getId, request.getId()));
    }

}
